package com.smh.a06zipStreamDemo1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipStreamDemo3 {
    public static void main(String[] args) throws IOException {

        File src = new File("day27-code\\file\\demo4\\test");
        //src的父级路径即(day27-code\file\demo4)
        File destParent = src.getParentFile();

        File dest = new File(destParent, src.getName() + ".zip");

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));
//        作用:获取src里面的每一个文件，变成zipEntry对象，放入到压缩包当中
//        参数一:数源
//        参数二:压缩流
//        参数三:压缩包内部的路径
        toZip(src, zos, "");

        zos.close();


    }

    public static void toZip(File src, ZipOutputStream zos, String name) throws IOException {
        if (src.isFile()) {

            FileInputStream fis = new FileInputStream(src);
            byte[] bytes = new byte[1024 * 1024];
            int len;
            ZipEntry entry = new ZipEntry(name + "\\" + src.getName());
            zos.putNextEntry(entry);
            while ((len = fis.read(bytes)) != -1) {
                zos.write(bytes, 0, len);
            }
            zos.closeEntry();
        } else {
            File[] files = src.listFiles();
            if (files != null) {
                for (File file : files) {
                    toZip(file, zos, name + "\\" + src.getName());
                }
            }

        }
        //结构有点问题,修改一下即先便利文件,在进行处理,为了使Zip内部路径正确.
    }

//    if (src.isFile()){
//            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(dest,src.getName())));
//            ZipEntry entry = new ZipEntry(dest.getPath()+src.getName());
//            zos.putNextEntry(entry);
//
//            FileInputStream fis = new FileInputStream(src);
//            byte[] bytes = new byte[1024*1024];
//            int len;
//            while((len=fis.read(bytes))!=-1){
//                zos.write(bytes,0,len);
//            }
//
//            fis.close();
//            zos.closeEntry();
//            zos.close();
//        }else {
//            File newDest = new File(dest,src.getName());
//            newDest.mkdirs();
//            File[] files = src.listFiles();
//            if (files!=null){
//                for (File file : files) {
//                    toZip(file,newDest);
//                }
//            }
//        }
}
